package com.blrs.system.service.impl;

import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSONArray;
import com.blrs.common.constant.CacheConstants;
import com.blrs.common.core.redis.RedisCache;
import com.blrs.common.utils.ReflectionUtils;
import com.blrs.system.domain.SysUserRole;
import com.blrs.system.mapper.SysUserMapper;
import com.blrs.system.mapper.SysUserRoleMapper;
import com.blrs.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.blrs.common.annotation.DataScope;
import com.blrs.common.constant.UserConstants;
import com.blrs.common.core.domain.TreeSelect;
import com.blrs.common.core.domain.entity.SysDept;
import com.blrs.common.core.domain.entity.SysRole;
import com.blrs.common.core.domain.entity.SysUser;
import com.blrs.common.core.text.Convert;
import com.blrs.common.exception.ServiceException;
import com.blrs.common.utils.SecurityUtils;
import com.blrs.common.utils.StringUtils;
import com.blrs.common.utils.spring.SpringUtils;
import com.blrs.system.mapper.SysDeptMapper;
import com.blrs.system.mapper.SysRoleMapper;

/**
 * 部门管理 服务实现
 *
 * @author ruoyi
 */
@Service
public class SysDeptServiceImpl implements ISysDeptService
{
    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private RedisCache redisCache;

    /**
     * 查询部门管理数据
     *
     * @param dept 部门信息
     * @return 部门信息集合
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<SysDept> selectDeptList(SysDept dept)
    {
        //Long dataScope = gettdataScope(SecurityUtils.getUserId());
        /*JSONArray arrayCache=redisCache.getCacheObject(CacheConstants.DEPT_KEY+"dept");
        //判断缓存中是否有部门信息
        if(!StringUtils.isNotNull(arrayCache)){
            redisCache.setCacheObject(CacheConstants.DEPT_KEY+"dept",deptMapper.selectDeptList(new SysDept()));
        }*/
        Long userId = SecurityUtils.getUserId();
        if(userId!=1&&userId!=2){
            dept.setBelongTo(SecurityUtils.getOrgId().toString());
        }
        List<SysDept> deptList = deptMapper.selectDeptList(dept);
        for(int i=0;i<deptList.size();i++){
            deptList.get(i).setEmail(SecurityUtils.getOrgId().toString());
        }
        return deptList;
    }

    @Override
    public List<SysDept> selectDeptListAll(SysDept dept) {
        return deptMapper.selectDeptListAll(dept);
    }

    @Override
    public List<SysDept> selectDeptListByEnterpriseInfo(SysDept dept)
    {
        List<SysDept> deptList = deptMapper.selectDeptListByEnterpriseInfo(dept);
        for(int i=0;i<deptList.size();i++){
            deptList.get(i).setEmail(SecurityUtils.getOrgId().toString());
        }
        return deptList;
    }
    /**
     * 查询部门管理数据
     *
     * @param dept 部门信息
     * @return 部门信息集合
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<SysDept> selectDeptListByIsCertified(SysDept dept)
    {
        List<SysDept> deptList = deptMapper.selectDeptListByIsCertified(dept);

        return deptList;
    }
    //入驻企业审核
    @Override
    public int enterpriseVerify(SysDept dept) {
        int count;
        //审核通过 修改角色 根据用户注册的企业类别修改所属角色端口管理员
        //企业类别：0:工业企业 1：服务机构 2 ：园区平台
        //角色端口:739:企业端 740:园区平台端 741:服务端
        if(dept.getIsCertified().equals("2")){//代表审核通过
            SysUser user = new SysUser();
            user.setDeptId(dept.getDeptId());
            user.setIsAdmin("1");

            //根据机构id 查询用户
            List<SysUser> userList = userMapper.selectUserList(user);
            //先删用户角色信息再新增
            userRoleMapper.deleteUserRoleByUserId(userList.get(0).getUserId());
            Long roleId = 0l;
            if(dept.getCompanyType().equals("0")){
                roleId = 739L;
            }else if(dept.getCompanyType().equals("1")){
                roleId = 741L;
            }else if(dept.getCompanyType().equals("2")){
                roleId = 740L;
            }
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            SysUserRole ur = new SysUserRole();
            ur.setUserId(userList.get(0).getUserId());
            ur.setRoleId(roleId);
            list.add(ur);
            userRoleMapper.batchUserRole(list);
            count = deptMapper.updateDept(dept);
        }else{
            dept.setIsCertified("3");
            count = deptMapper.updateDept(dept);
        }
        return count;
    }
    @Override
    public List<SysDept> selectDeptListByProduct(SysDept dept) {
        dept.setDeptId(SecurityUtils.getOrgId());
        return deptMapper.selectDeptListByProduct(dept);
    }

    @Override
    public List<SysDept> selectDeptListByProductType(SysDept dept) {
        dept.setDeptId(SecurityUtils.getOrgId());
        return deptMapper.selectDeptListByProductType(dept);
    }

    @Override
    public List<SysDept> selectDeptListIndex(SysDept dept)
    {

        return deptMapper.selectDeptListIndex(dept);
    }

    @Override
    public Long selectDeptListIndexCount(SysDept dept) {
       return deptMapper.selectDeptListIndexCount(dept);
    }

    @Override
    public int selectDeptByDeptNameAll(String deptName) {
        return deptMapper.selectDeptByDeptNameAll(deptName);
    }

    /**
     * 用于平台管理中选择所有运营商（机构）
     * @param dept
     * @return
     */
    @Override
    public List<SysDept> selectOrgListAll(SysDept dept) {
        return deptMapper.selectOrgListByPlatform(dept);
    }


    /**
     * 查询部门树结构信息
     *
     * @param dept 部门信息
     * @return 部门树信息集合
     */
    @Override
    public List<TreeSelect> selectDeptTreeList(SysDept dept)
    {
        List<SysDept> depts=null;

        if(SecurityUtils.getUserId()==1||SecurityUtils.getUserId()==2){
            //管理员查看所有机构
            depts = deptMapper.selectDeptAll();
        }else{
            //不是超级管理员或平台管理员 查询自己机构下的部门树
            dept.setDeptId(SecurityUtils.getOrgId());
            dept.setAncestors(String.valueOf(SecurityUtils.getOrgId()));
            depts = deptMapper.selectChildrenDeptByIdAndSelf(SecurityUtils.getOrgId());
        }
        /*if (dept.getIsOrg()==1){
          dept.setDeptId(SecurityUtils.getOrgId());
          dept.setAncestors(String.valueOf(SecurityUtils.getOrgId()));
          depts = deptMapper.selectChildrenDeptByIdAndSelf(SecurityUtils.getOrgId());
        }else {
          depts = SpringUtils.getAopProxy(this).selectDeptList(dept);
        }*/
        List<TreeSelect> treeSelects = buildDeptTreeSelect(depts);
        return treeSelects;
    }

    @Override
    public SysDept getParentId(String deptId)
    {
        SysDept data =  deptMapper.getParentId(deptId);
        return data;
    }
    /**
     * 构建前端所需要树结构
     *
     * @param depts 部门列表
     * @return 树结构列表
     */
    @Override
    public List<SysDept> buildDeptTree(List<SysDept> depts)
    {
        List<SysDept> returnList = new ArrayList<SysDept>();
        List<Long> tempList = depts.stream().map(SysDept::getDeptId).collect(Collectors.toList());
        for (SysDept dept : depts)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId()))
            {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param depts 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildDeptTreeSelect(List<SysDept> depts)
    {
        List<SysDept> deptTrees = buildDeptTree(depts);
        //把人员也进行树结构处理
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 根据角色ID查询部门树信息
     *
     * @param roleId 角色ID
     * @return 选中部门列表
     */
    @Override
    public List<Long> selectDeptListByRoleId(Long roleId)
    {
        SysRole role = roleMapper.selectRoleById(roleId);
        return deptMapper.selectDeptListByRoleId(roleId, role.isDeptCheckStrictly());
    }

    /**
     * 根据部门ID查询信息
     *
     * @param deptId 部门ID
     * @return 部门信息
     */
    @Override
    public SysDept selectDeptById(Long deptId)
    {
        return deptMapper.selectDeptById(deptId);
    }
    //重新获取当前登录人员的组织机构id
    @Override
    public Long getOrgId(){
        Long orgId;
        //当前所属部门
        String deptName = SecurityUtils.getLoginUser().getUser().getDept().getDeptName();
        SysDept dept = deptMapper.selectDeptById(SecurityUtils.getLoginUser().getDeptId());
        if(dept.getType().equals("0")){//如果等于部门
            String[] temp = dept.getAncestors().split(",");
            //最顶层机构部门id
            orgId = Long.parseLong(temp[1]);
        }else{
            orgId = SecurityUtils.getOrgId();
        }
        return orgId;
    }
    //重新获取当前登录人员的组织机构名称
    @Override
    public String getOrgName(){
        String orgName;
        //获取当前登录人员部门信息
        SysDept dept = deptMapper.selectDeptById(SecurityUtils.getLoginUser().getDeptId());
        if(dept.getType().equals("0")){//如果等于部门
            String[] temp = dept.getAncestors().split(",");
            //获取最顶级机构的名称
            SysDept parentDept = deptMapper.selectDeptById(Long.parseLong(temp[1]));
            orgName = parentDept.getDeptName();
        }else{
            orgName = SecurityUtils.getOrgName();
        }
        return orgName;
    }
    /**
     * 根据ID查询所有子部门（正常状态）
     *
     * @param deptId 部门ID
     * @return 子部门数
     */
    @Override
    public int selectNormalChildrenDeptById(Long deptId)
    {
        return deptMapper.selectNormalChildrenDeptById(deptId);
    }

    /**
     * 是否存在子节点
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public boolean hasChildByDeptId(Long deptId)
    {
        int result = deptMapper.hasChildByDeptId(deptId);
        return result > 0;
    }

    /**
     * 查询部门是否存在用户
     *
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(Long deptId)
    {
        int result = deptMapper.checkDeptExistUser(deptId);
        return result > 0;
    }

    /**
     * 校验部门名称是否唯一
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public boolean checkDeptNameUnique(SysDept dept)
    {
        Long deptId = StringUtils.isNull(dept.getDeptId()) ? -1L : dept.getDeptId();
        SysDept info = deptMapper.checkDeptNameUnique(dept.getDeptName(), dept.getParentId());
        if (StringUtils.isNotNull(info) && info.getDeptId().longValue() != deptId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public SysDept selectDeptByDeptName(SysDept dept)
    {

        return deptMapper.selectDeptByDeptName(dept);
    }

    /**
     * 校验部门是否有数据权限
     *
     * @param deptId 部门id
     */
    @Override
    public void checkDeptDataScope(Long deptId)
    {
        if (!SysUser.isAdmin(SecurityUtils.getUserId()))
        {
            SysDept dept = new SysDept();
            dept.setDeptId(deptId);
            List<SysDept> depts = SpringUtils.getAopProxy(this).selectDeptList(dept);
            /*if (StringUtils.isEmpty(depts))
            {
                throw new ServiceException("没有权限访问部门数据！");
            }*/
        }
    }

    /**
     * 新增保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public int insertDept(SysDept dept)
    {
        SysDept info = deptMapper.selectDeptById(dept.getParentId());
        if (StringUtils.isNotNull(info)){
            if(SecurityUtils.getUserId()!=1&&SecurityUtils.getUserId()!=2){
                dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
            }
        }else{
            dept.setAncestors("0");
        }
        /*// 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus()))
        {
            throw new ServiceException("部门停用，不允许新增");
        }*/

        if(dept.getType().equals("0")){//如果添加的是部门 则需要把归属机构的机构类别添加进去 否则无法进行登录
            SysDept data = new SysDept();
            data = deptMapper.selectDeptById(SecurityUtils.getOrgId());
            dept.setCompanyType(data.getCompanyType());
            dept.setBelongTo(SecurityUtils.getOrgId().toString());
            dept.setIsCertified("2");
        }
        int row = deptMapper.insertDept(dept);
        redisCache.setCacheObject(CacheConstants.DEPT_KEY+"dept",deptMapper.selectDeptList(new SysDept()));
        return row;
    }
    @Override
    public Long gettdataScope(Long userId)
    {
        return deptMapper.gettdataScope(userId);
    }

    /**
     * 修改保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public int updateDept(SysDept dept)
    {
        SysDept newParentDept = deptMapper.selectDeptById(dept.getParentId());
        SysDept oldDept = deptMapper.selectDeptById(dept.getDeptId());
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept))
        {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
        }
        //dept.setBelongTo(SecurityUtils.getOrgId().toString());
        int result = deptMapper.updateDept(dept);
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()) && StringUtils.isNotEmpty(dept.getAncestors())
                && !StringUtils.equals("0", dept.getAncestors()))
        {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatusNormal(dept);
        }
        redisCache.setCacheObject(CacheConstants.DEPT_KEY+"dept",deptMapper.selectDeptList(new SysDept()));
        return result;
    }

    /**
     * 修改该部门的父级部门状态
     *
     * @param dept 当前部门
     */
    private void updateParentDeptStatusNormal(SysDept dept)
    {
        String ancestors = dept.getAncestors();
        Long[] deptIds = Convert.toLongArray(ancestors);
        deptMapper.updateDeptStatusNormal(deptIds);
    }

    /**
     * 修改子元素关系
     *
     * @param deptId 被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors)
    {
        List<SysDept> children = deptMapper.selectChildrenDeptById(deptId);
        for (SysDept child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            deptMapper.updateDeptChildren(children);
        }
    }

    /**
     * 删除部门管理信息
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public int deleteDeptById(Long deptId)
    {
        int row= deptMapper.deleteDeptById(deptId);
        //redisCache.setCacheObject(CacheConstants.DEPT_KEY+"dept",deptMapper.selectDeptList(null));
        return row;
    }

    @Override
    public List<SysDept> selectDeptList() {
        List<SysDept> sysDeptList=deptMapper.ListDept(1L);
        return buildDeptTree(sysDeptList);
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysDept> list, SysDept t)
    {
        // 得到子节点列表
        List<SysDept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDept tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysDept> getChildList(List<SysDept> list, SysDept t)
    {
        List<SysDept> tlist = new ArrayList<SysDept>();
        Iterator<SysDept> it = list.iterator();
        while (it.hasNext())
        {
            SysDept n = (SysDept) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getDeptId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDept> list, SysDept t)
    {
        return getChildList(list, t).size() > 0;
    }

    public  SysDept getOrg(SysDept t){
        List<SysDept> list=null;
        JSONArray arrayCache=redisCache.getCacheObject(CacheConstants.DEPT_KEY+"dept");
        //判断缓存中是否有部门信息
        if(!StringUtils.isNotNull(arrayCache)){
            list=deptMapper.selectDeptList(new SysDept());
            redisCache.setCacheObject(CacheConstants.DEPT_KEY+"dept",list);
        }
        else{
            list=arrayCache.toList(SysDept.class);
        }
        return getOrg(list, t);
    }

    @Override
    public List<TreeSelect> selectDeptTreeListByEle(Long id) {
       Long orgId=this.selectTreeByEle(id);
        SysDept sysDept = new SysDept();
        sysDept.setDeptId(orgId);
       //把所有下面的部门查询出来
        List<SysDept> deptList = deptMapper.selectChildrenDeptByIdAndSelf(sysDept.getDeptId());
        List<TreeSelect> treeSelects = buildDeptTreeSelect(deptList);
        return treeSelects;
    }

    @Override
    public List<SysDept> selectOrgList(SysDept dept) {
      return deptMapper.selectOrgListBySea(dept);
    }

    @Override
    public String importUser(List<SysDept> deptList) {
        if (StringUtils.isNull(deptList) || deptList.size() == 0) {
            throw new ServiceException("导入企业数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (SysDept dept : deptList) {
            try {
                if (StringUtils.isEmpty(dept.getDeptName())) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、企业名称为空！ ");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、数据导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            for (SysDept dept : deptList) {
                dept.setStatus("0");
                dept.setDelFlag("0");
                dept.setParentId(0L);
                dept.setAncestors("0");
                dept.setType("1");
                dept.setIsCertified("0");
                dept.setCreateBy(SecurityUtils.getUsername());
                dept.setCreateTime(new Timestamp(new Date().getTime()));
                dept.setBelongTo(SecurityUtils.getOrgId().toString());
                try {
                    ReflectionUtils.setCommonPrivateProperty(dept);
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                deptMapper.insertDept(dept);
                successNum++;
                successMsg.append("<br/>" + successNum + "、商机信息数据导入成功");
            }
            successMsg.insert(0, "恭喜您，导入企业数据 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }



    private Long selectTreeByEle(Long id) {
        SysDept sysDept = deptMapper.selectDeptById(id);
        while (sysDept != null && !sysDept.getType().equals("1")) {
            sysDept = deptMapper.selectDeptById(sysDept.getParentId());
        }
        return sysDept == null ? null : sysDept.getDeptId();
    }


    private List<TreeSelect> buildDeptTreeUserList(List<SysDept> depts) {
        List<SysDept> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 根据部门获取组织机构
     */

    private SysDept getOrg(List<SysDept> list, SysDept t){
        SysDept sysDept=null;
        if(t.getType()!=null){
            if(t.getType().equals("1")){
                return t;
            }else{
                Iterator<SysDept> it = list.iterator();
                while(it.hasNext()){ //判断是否有迭代元素
                    SysDept s = it.next();//获取迭代出的元素
                    if(t.getParentId().equals(s.getDeptId())){
                        if(s.getType().equals("1")){
                            return s;
                        }
                        else{
                            getOrg(list,s);
                        }
                    }else{
                        continue;
                    }
                }
            }
        }
        return sysDept;
    }
}
